<template>
  <div class="delivery-way">
    <div class="sticky left-0 right-0 top-0 z-9 h-full bg-hex-ffffff">
      <div class="relative">
        <div class="z-999 flex items-center justify-between px-20rpx" :style="{ paddingTop: `${searchBarTop}px` }" @click.stop="goback">
          <uni-icons type="back" size="28" />
          <span class="text-center text-36rpx font-600">我的订单</span>
          <div class="text-hex-fff">111</div>
        </div>
      </div>
      <div class="mt-36rpx flex items-center justify-center pb-10rpx">
        <div class="h-64rpx w-392rpx flex items-center justify-between rounded-60rpx bg-hex-ABCD03 px-4rpx text-28rpx text-hex-fff">
          <div v-for="item in titleList" :key="item.id" class="h-56rpx w-192rpx rounded-56rpx text-center leading-56rpx"
               :class="{ 'text-hex-ABCD03 bg-hex-fff': tabIndex === item.id }" @click="toggleTab(item)">{{ item.name }}</div>
        </div>
      </div>
      <div v-if="tabIndex === 2">
        <nav-bar ref="mallOrder" :nav-data="cloumnList" :type="'mall'" :curIndex="currentTab" @handleSwitchBar="handTabClick" />
      </div>
    </div>
    <div v-if="tabIndex===1">
      <div
        v-for="item in dataList"
        class="flex justify-center"
        @click.stop="goOrderDetail(item.businessId)">
        <div
          class="mt-40rpx box-border w-686rpx rounded-24rpx px-36rpx shadow">
          <div class="h-96rpx flex items-center justify-between">
            <div class="item-center flex">
              <text class="inline-block h-36rpx w-60rpx flex items-center justify-center rounded-4rpx bg-hex-C5AD8A text-20rpx text-hex-fff">
                {{ item.deliveryType === 2?'自提':'外卖' }}
              </text>
              <text class="ml-12rpx text-28rpx font-600 text-hex-333">{{ item.storeName }}</text>
              <div v-if="item.pickUpNumber" class="ml-12rpx flex items-center text-26rpx font-600 text-hex-ABCD03">
                取餐码:{{ item.pickUpNumber }}
              </div>
            </div>
            <div class="text-24rpx text-hex-333">
              <span>
                {{ teaOrderStatus[item.orderStatus] }}
              </span>
            </div>
          </div>
          <div class="h-2rpx w-full bg-hex-f5f5f5" />
          <!-- 商品卡片 -->
          <div v-for="shop in item.childList" class="mt-32rpx flex">
            <div 
              class="relative mr-24rpx mt-24rpx h-180rpx w-180rpx overflow-hidden rounded-16rpx">
              <image
                class="absolute left-50% top-50% h-180rpx w-180rpx rounded-16rpx"
                style="transform: translate(-50%, -50%);" :src="shop.productImage" mode="aspectFill" />
            </div>
            <div class="flex-1 flex-col text-hex-333">
              <div class="w-full flex flex-1 justify-between">
                <div class="text-28rpx font-600">{{ shop.productName }}</div>
                <div>
                  <div class="mb-4rpx text-right text-28rpx">￥{{ shop.flowPrice }}</div>
                  <!-- <div class="text-right text-24rpx text-hex-7C8699 line-through">￥{{ shop.originalPrice }}</div> -->
                </div>
              </div>
              <div class="mt-32rpx flex justify-between text-24rpx text-hex-7C8699">
                <div class="flex items-center justify-between">
                  <div>{{ shop.specs }}</div>
                </div>
                <div class="text-24rpx">x{{ shop.productQuantity }}</div>
              </div>
            </div>
          </div>

          <div class="mb-32rpx mt-52rpx flex justify-between text-24rpx text-hex-7C8699">
            <!-- <div>2023-05-01 12:23</div> -->
            <div class="text-hex-7C8699">
              <div v-if="item.orderStatus === 0 && endSec">
                <uni-countdown :show-day="false"
                               :minute="getCountDown(formatTime(item.createTime, 'YYYY/MM/DD HH:mm:ss'), 'm')"
                               :second="getCountDown(formatTime(item.createTime, 'YYYY/MM/DD HH:mm:ss'), 's')" color="#E36043" @timeup="timeup" />
              </div>
              <div v-else>
                {{ formatTime(item.createTime, 'YYYY-MM-DD HH:mm') }}
              </div>
            </div>
            <div class="text-hex-333">共{{ item.totalQuantity }}件商品,小计￥{{ item.payAmount }}</div>
          </div>
          <div v-if="item.orderStatus===1 || item.orderStatus ===2 || item.orderStatus===4 || item.orderStatus===5"
               class="mb-32rpx flex items-center justify-end text-28rpx">
            <div class="flex">
              <div
                class="h-72rpx w-198rpx border-2rpx border-hex-ABCD03 rounded-72rpx border-solid text-center leading-72rpx text-hex-ABCD03"
                @click.stop="anotherOrder(item.id)">再来一单</div>
            </div>
          </div>
          <div v-if="item.orderStatus===3" class="mb-32rpx flex items-center justify-end text-28rpx">
            <div class="flex">
              <div
                v-if="item.evaluationState===0"
                class="h-72rpx w-198rpx border-2rpx border-hex-ABCD03 rounded-72rpx border-solid text-center leading-72rpx text-hex-ABCD03"
                @click.stop="navTo(`/pages-tea/handleComments?businessId=${item.businessId}&appType=2`)">
                评价
              </div>
              <div
                class="ml-32rpx h-72rpx w-198rpx rounded-72rpx bg-hex-E36043 text-center leading-72rpx text-hex-fff"
                @click.stop="anotherOrder(item.id)">再来一单</div>
            </div>
          </div>
          <div v-if="item.orderStatus===0" class="mb-32rpx flex items-center justify-end text-28rpx">
            <div class="flex">
              <div
                class="h-72rpx w-198rpx border-2rpx border-hex-ABCD03 rounded-72rpx border-solid text-center leading-72rpx text-hex-ABCD03"
                @click.stop="cancelOrder(item.businessId)">
                立即取消
              </div>
              <div
                class="ml-32rpx h-72rpx w-198rpx rounded-72rpx bg-hex-E36043 text-center leading-72rpx text-hex-fff"
                @click.stop="goPay(item.businessId)">
                立即支付
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="dataList.length===0">
        <div class="mt-230rpx flex flex-col items-center">
          <div class="image">
            <image
              :src="`${cdnUrl}/imgs/noOpen/noText.png${imgVersion}`"
              mode="scaleToFill"
              class="h-364rpx w-364rpx"
            />
          </div>
          <div class="mb-64rpx text-28rpx text-hex-7C8699">暂无数据</div>
        </div>
      </div>
    </div>
    <div v-if="tabIndex===2">
      <div v-for="item in shopOrderList" class="flex justify-center" @click="navTo(`/pages-mine/orderdetails?businessId=${item.businessId}`)">
        <div
          class="mt-40rpx box-border w-686rpx rounded-24rpx px-36rpx shadow">
          <div class="h-96rpx flex items-center justify-between">
            <div class="item-center flex">
              <text class="ml-12rpx text-28rpx font-600 text-hex-333">{{ item.storeName }}</text></div>
            <div class="text-24rpx text-hex-333">
              <span>{{ mallOrderStatus[item.showStatus]||'处理中' }}</span>
            </div>
          </div>
          <div class="h-2rpx w-full bg-hex-f5f5f5" />
          <!-- 商品卡片 -->
          <div v-for="shop in item.childList" class="mt-32rpx flex">
            <div class="mr-24rpx min-h-140rpx min-w-140rpx flex items-center justify-center rounded-26rpx bg-hex-F5F3F0">
              <image
                :src="shop.productImage"
                mode="scaleToFill"
                class="h-107rpx w-74rpx"
              />
            </div>
            <div class="w-full flex-col text-hex-333">
              <div class="w-full flex flex-1 justify-between">
                <div class="text-28rpx font-600">{{ shop.productName }}</div>
                <div>
                  <div class="mb-4rpx text-right text-28rpx">￥{{ shop.flowPrice }}</div>
                  <!-- <div class="text-right text-24rpx text-hex-7C8699 line-through">￥{{ shop.originalPrice }}</div> -->
                </div>
              </div>
              <div class="mt-32rpx flex justify-between text-24rpx text-hex-7C8699">
                <div class="flex items-center justify-between">
                  <div>{{ shop.specs }}</div>
                </div>
                <div class="text-24rpx">x{{ shop.productQuantity }}</div>
              </div>
            </div>
          </div>

          <div class="mb-32rpx mt-52rpx flex justify-between text-24rpx text-hex-7C8699">
            <!-- <div>2023-05-01 12:23</div> -->
            <div class="text-hex-7C8699">
              <div v-if="item.orderStatus === 0">
                <uni-countdown :show-day="false"
                               :minute="getCountDown(item.createTime, 'm')"
                               :second="getCountDown(item.createTime, 's')" color="#E36043" @timeup="timeup" />
              </div>
              <div v-else>
                {{ formatTime(item.createTime, 'YYYY-MM-DD HH:mm') }}
              </div>
            </div>
            <div class="text-hex-333">共{{ item.totalQuantity }}件商品,小计￥{{ item.payAmount }}</div>
          </div>
          <!-- 待支付操作 -->
          <div v-if="mallOrderStatus[item.showStatus] === '待支付'" class="mb-32rpx w-100% text-28rpx">
            <div class="flex items-center">
              <div class="text-28rpx text-hex-7C8699" @click.stop="cancelOrder(item.businessId)">取消订单</div>
              <div class="ml-26rpx flex flex-1 justify-end">
                <!-- <div class="h-72rpx w-198rpx border-2rpx border-hex-7C8699 rounded-72rpx border-solid text-center leading-72rpx text-hex-7C8699">
                  修改地址
                </div> -->
                <div class="ml-32rpx h-72rpx w-198rpx border-2rpx border-hex-ABCD03 rounded-72rpx border-solid text-center leading-72rpx text-hex-ABCD03"
                     @click.stop="goPay(item.businessId)">
                  立即支付
                </div>
              </div>
            </div>
          </div>
          <div v-else-if="mallOrderStatus[item.showStatus] === '已取消'" class="mb-32rpx w-100% text-28rpx" />
          <div v-else-if="mallOrderStatus[item.showStatus] === '待发货'" class="mb-32rpx w-100% text-28rpx">
            <div class="flex items-center">
              <div class="text-28rpx text-hex-7C8699" @click.stop="navTo(`/pages-shop/afterSalesApplication?businessId=${item.businessId}&refundAmount=${item.payAmount}`)">申请售后</div>
              <div class="ml-26rpx flex flex-1 justify-end">
                <div class="h-72rpx w-198rpx border-2rpx border-hex-7C8699 rounded-72rpx border-solid text-center leading-72rpx text-hex-7C8699"
                     @click.stop="remind">提醒发货</div>
                <!-- <div class="ml-32rpx h-72rpx w-198rpx border-2rpx border-hex-ABCD03 rounded-72rpx border-solid text-center leading-72rpx text-hex-ABCD03">修改地址</div> -->
              </div>
            </div>

          </div>
          <div v-else-if="mallOrderStatus[item.showStatus] === '待收货'" class="mb-32rpx w-100% text-28rpx">
            <div class="ml-26rpx flex flex-1 justify-end">
              <div class="h-72rpx w-198rpx border-2rpx border-hex-7C8699 rounded-72rpx border-solid text-center leading-72rpx text-hex-7C8699">查看物流</div>
              <div class="ml-32rpx h-72rpx w-198rpx border-2rpx border-hex-ABCD03 rounded-72rpx border-solid text-center leading-72rpx text-hex-ABCD03"
                   @click.stop="confirmDelivery(item.businessId)">确定收货</div>
            </div>
          </div>
          <div v-else-if="mallOrderStatus[item.showStatus] === '已完成'" class="mb-32rpx w-100% text-28rpx">
            <!-- <div class="flex items-center justify-between bg-hex-F5F5F5 p-24rpx">
              <span class="text-24rpx text-hex-E36043">等待商家处理</span>
              <span class="text-24rpx text-hex-7C8699">申请事件 2023-7-19</span>
            </div> -->
            <div class="mt-24rpx flex items-center">
              <div class="text-28rpx text-hex-7C8699"
                   @click.stop="navTo(`/pages-shop/afterSalesApplication?businessId=${item.businessId}&refundAmount=${item.payAmount}`)">
                申请售后
              </div>
              <div class="ml-26rpx flex flex-1 justify-end">
                <div
                  class="ml-32rpx h-72rpx w-198rpx border-2rpx border-hex-ABCD03 rounded-72rpx border-solid text-center leading-72rpx text-hex-ABCD03"
                  @click.stop="navTo(`/pages-tea/handleComments?businessId=${item.businessId}&appType=3`)">评价</div>
              </div>
            </div>
          </div>
          <div v-else class="mb-32rpx w-100% text-28rpx">
            <div class="flex items-center">
              <div class="ml-26rpx flex flex-1 justify-end">
                <div class="h-72rpx w-198rpx border-2rpx border-hex-7C8699 rounded-72rpx border-solid text-center leading-72rpx text-hex-7C8699"
                     @click.stop="navTo(`/pages-mine/aftersales-details?businessId=${item.businessId}`)">查看售后</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="shopOrderList.length===0"
           class="mt-200rpx flex items-center justify-center">
        <div>
          <image
            class="h-364rpx w-364rpx"
            :src="`${cdnUrl1}/imgs/xy/other/noneeattention.png${imgVersion}`"
            mode="scaleToFill"
          />
          <div class="text-center text-28rpx text-hex-7C8699">暂无数据</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>

let tabIndex = $ref(1)
onLoad((options) => {
  // #ifndef H5
  let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  searchBarTop = menuButtonInfo.top
  // #endif
  if (options && options.appType) {
    switch (options.appType) {
      case '2':
        tabIndex = 1
        break
      case '3':
        tabIndex = 2
        break
      default:
        tabIndex = 1
        break
    }
  }
})
const titleList = [
  { id: 1, name: '茶饮订单' },
  { id: 2, name: '商城订单' },
]
const userStores = useUserStore()
let cloumnList: any = $ref([
  { id: 0, name: '全部' },
  { id: 1, name: '待支付' },
  { id: 2, name: '待发货' },
  { id: 3, name: '待收货' },
  { id: 4, name: '售后退款' },

])
const teaOrderStatus = {
  0: '待支付',
  1: '已取消',
  2: '进行中',
  3: '已完成',
  4: '退款中',
  5: '已取消',
}


let currentTab = $ref(0)
const toggleTab = (item) => {
  tabIndex = item.id
  if (tabIndex === 1) {
    pageNo = 1
    dataList = []
    getOrderList()
  }
}

let mallOrder: any = $ref(null)
const handTabClick = (item) => {
  currentTab = item.id
  pageNo1 = 1
  shopOrderList = []
  getShopOrderList(item.id)
}
let dataList: any = $ref([])
const goback = () => {
  uni.switchTab({
    url: '/pages/mine',
  })
}
let searchBarTop: any = $ref('24')

const goOrderDetail = (id) => {
  navTo(`/pages-tea/paySuccess?businessId=${id}`)
}
let pageNo: any = $ref(1)
let isHandleGetMoreList: any = $ref(false)
const getOrderList = async () => {
  const reqData = {
    method: 'post',
    data: {
      'pageNo': pageNo,
      'pageSize': 10,
    },
    headers: { AppType: 2, UserId: userStores.user.id },
  }
  const { status, data, error } = await Fetch('/qqyapi/order/order/pageList', reqData)
  if (status !== 200 && data.code !== 0) {
    return
  }
  if (data.code === 0) {
    dataList = dataList.concat(data?.result?.list)
    dataList.forEach((item) => {
      let tempBoolean: any = ''
      tempBoolean = item.childList.some((itemGoods) => {
        return itemGoods.evaluationState === 1
      })
      if (tempBoolean) {
        item.orderEvaluationStatus = 1
      } else {
        item.orderEvaluationStatus = 0
      }
    })
    if (dataList.length < Number(data?.result.total)) {
      isHandleGetMoreList = true
      return
    }
    isHandleGetMoreList = false
  }
}

let shopOrderList: any = $ref([])
let pageNo1 = $ref(1)
let isLoadMore = $ref(false)
let getShopOrderList = async (filterId) => {
  const reqData = {
    method: 'post',
    headers: { UserId: userStores.user.id },
    data: {
      orderType: filterId,
      pageNo: pageNo1,
      pageSize: 10,
    },
  }
  const { data, status } = await Fetch('/qqyapi/order/order/shop/pageList', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  shopOrderList = [...shopOrderList, ...data?.result?.list]
  shopOrderList.forEach(item => {
    item.showStatus = (item.orderStatus).toString() + (item.deliveryStatus).toString() + (item.afterSaleState).toString()
  })
  if (shopOrderList.length < Number(data?.result.total)) {
    isLoadMore = true
    return
  }
  isLoadMore = false
}

//下滑加载更多数据
const getMoreData = () => {
  if (tabIndex === 1) {
    if (isHandleGetMoreList) {
      pageNo++
      getOrderList()
    }
  } else {
    if (isLoadMore) {
      pageNo1++
      getShopOrderList(currentTab)
    }
  }
}
onReachBottom(() => {
  getMoreData()
})
//立即支付
const goPay = async (bussinessId) => {
  const reqData = {
    method: 'post',
    data: {
      orderBusinessId: bussinessId,
    },
  }
  uni.showLoading({ title: 'Loading...' })
  const { data, status, error } = await Fetch('/qqyapi/payment/checkoutCounter/prepay', reqData)
  if (status === 200 && data.code === 0) {
    let params = data.result
    uni.requestPayment({
      'provider': 'wxpay', // 服务提提供商
      'orderInfo': {},
      'nonceStr': params.nonceStr,
      'package': params.packageVal,
      'signType': params.signType,
      'paySign': params.paySign,
      'timeStamp': params.timeStamp,
      success() {
        uni.hideLoading()
        if (tabIndex === 1) {
          dataList = []
          pageNo = 1
          getOrderList()
        } else {
          mallOrder.changeNav(0, { id: 0 })
        }
      },
      fail() {
        uni.hideLoading()
        uni.showToast({ title: '取消支付' })
      },
    })
  }
}
// 再来一单
const anotherOrder = async (orderId) => {
  const reqData = {
    method: 'post',
    data: {
      'orderId': orderId,
      trolleyType: '2',
      userId: userStores.user.id,
    },
    headers: { UserId: userStores.user.id },
  }
  uni.showLoading({ title: 'Loading...' })
  const { status, data, error } = await Fetch('/qqyapi/order/trolley/anotherOrder', reqData)
  if (status !== 200 || data.code !== 0) {
    uni.hideLoading()
    return
  }
  if (data.code === 0) {
    uni.hideLoading()
    uni.switchTab({ url: '/pages/index' })
    uni.$emit('teaIndexOpenTeaGoodsCarPop')
  }
}

// 取消订单
const cancelOrder = async (businessId) => {
  const reqData = {
    method: 'post',
    data: {
      'businessId': businessId,
    },
    headers: {
      UserId: userStores.user.id,
    },
  }
  uni.showLoading({ title: 'Loading...' })
  const { status, data, error } = await Fetch('/qqyapi/order/order/cancelOrder', reqData)
  if (status !== 200 || data.code !== 0) {
    uni.hideLoading()
    return
  }
  if (data.code === 0) {
    uni.hideLoading()
    if (tabIndex === 1) {
      dataList = []
      pageNo = 1
      getOrderList()
    } else {
      mallOrder.changeNav(0, { id: 0 })
    }
  }
}
// 退款
const refundMoney = async (businessid) => {
  uni.showLoading({ title: 'Loading...' })
  const reqData = {
    method: 'post',
    data: {
      'businessId': businessid,
    },
    headers: {
      AppType: 2,
      UserId: userStores.user.id,
    },
  }
  const { status, data, error } = await Fetch('/qqyapi/order/order/refund', reqData)
  if (status !== 200 || data.code !== 0) {
    uni.hideLoading()
    return
  }
  if (data.code === 0) {
    uni.hideLoading()
    pageNo = 1
    dataList = []
    getOrderList()
  }
}
//确认收货
const confirmDelivery = async (businessid) => {
  uni.showLoading({ title: 'Loading...' })
  const reqData = {
    method: 'post',
    data: {
      'businessId': businessid,
    },
    headers: {
      UserId: userStores.user.id,
    },
  }
  const { status, data, error } = await Fetch('/qqyapi/order/order/confirmDelivery', reqData)
  if (status !== 200 || data.code !== 0) {
    uni.hideLoading()
    return
  }
  if (data.code === 0) {
    uni.hideLoading()
    mallOrder.changeNav(0, { id: 0 })
  }
}
//提醒发货
const remind = async () => {
  uni.showToast({ title: '已提醒', icon: 'none' })
}
let endSec = $ref(true)

const getCountDown = (time, type) => {
  let newTime: any = formatTime(time, 'YYYY/MM/DD HH:mm:ss')
  let dateTime: any = new Date(newTime).getTime() + 1000 * 60 * 15
  let curTime: any = new Date().getTime()
  let target: any = dateTime - curTime
  if (type === 'm') {
    if (target > 0) {
      let minutes = Math.floor((target / 1000 / 60) % 60)
      return minutes
    } else {
      return '0'
    }
  }
  if (type === 's') {
    if (target > 0) {
      let seconds = Math.floor((target / 1000) % 60)
      return seconds
    } else {
      endSec = false
      return '0'
    }
  }

}
const timeup = () => {
  endSec = false
  getOrderList()
}

onMounted(() => {
  getOrderList()
  getShopOrderList(0)
})
</script>

<style lang="scss">
.delivery-way{
  .triangle {
    width: 0;
    height: 0;
    border-left: 12rpx solid #000;
    border-top: 12rpx solid transparent;
    border-bottom:12rpx solid transparent;
  }
}
</style>
